import router from './router'
import store from './store'
// import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
// import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/404'] // no redirect whitelist

// 切换标题
router.beforeEach((to, from, next) => {
	document.title = getPageTitle(to.meta.title)
	next()
 })

router.beforeEach( async (to, from, next) => {
	NProgress.start()
	// console.log(to, from);
	// 1.如果有token && 去的登录页  --> 让它去主页
	// 2.如果没有token && 去的不是登录页  --> 去登录页
	const token = store.state.user.token
	if (token && to.path === '/login') {
		next('/')
		NProgress.done()
	} else if (!token && whiteList.includes(to.path) === false) {
		next('/login')
		NProgress.done()
	} else {
		// 调用action获取用户个人信息，保存到vuex
		if(!store.state.user.userInfo.userId && token){
			await store.dispatch('user/getUserInfo')
		}
		next()
	}
})


router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
